<template>
  <view class="PayList">
    <scroll-view scroll-x class="bg-white nav">
      <view class="flex text-center">
        <view class="cu-item flex-sub" :class="curTab===item.value?'text-orange cur':''" v-for="item in tabs" :key="item.value" @tap="tabSelect(item.value)">
          {{item.title}}
        </view>
      </view>
    </scroll-view>

    <view v-if="payList.length > 0">
      <view v-for="item in payList">
        <view class="cu-card" :key="item.JFD_ID" @tap="toDZGZ(item.PJNO)">
          <view class="cu-item shadow padding-sm card-item" style="margin-top: 20rpx;margin-bottom: 10rpx;">
            <view class="cu-list menu">
              <view class="cu-item">
                <!--                <view class="cu-avatar round lg" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big10006.jpg);"></view>-->
                <view class="content flex-sub">
                  <view class="text-black text-bold text-sm">
                    <text>单号： {{item.JFDNO}}</text>
                  </view>
                  <view class="text-gray text-sm flex">
                    <text>课程： {{item.CLASSNAME}}</text>
                  </view>

                  <view class="text-gray text-sm flex">
                    <text>学生姓名： {{item.STUDENTNAME}}</text>
                  </view>

                  <view class="text-gray text-sm flex">
                    <text>学号： {{item.STUDENTNO}}</text>
                  </view>
				  <view class="text-gray text-sm flex">
				    <text>备注： {{item.DISC}}</text>
				  </view>



                </view>
              </view>

              <view class="cu-item">
                <view class="flex flex-direction text-red text-df">
                  <view class="text-price">{{ getPrice(item.SFJE,false) }}</view>
                  <!--                <view class="text-price">{{ item.SFJE2 }}<text class="text-sm margin-left-xs text-gray">50周岁（含）以上</text></view>-->
                </view>
				<button v-if="item.STATE === '1'" class="cu-btn bg-red round shadow" @tap.stop="doPay(item.JFDNO,item.SFJE,item)" >立即支付</button>
                <button v-if="item.STATE === '2'" class="cu-btn bg-olive round shadow" @tap.stop="applyRefund(item.JFD_ID,item)">申请退款</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <load-more :status="loadStatus" v-if="payList.length > 0"/>
    <view v-else class="text-gray text-center margin-top text-sm">-- 暂无数据 --</view>
  </view>
</template>

<script lang="ts" setup>
import {ref, watch, watchEffect} from "vue";
import {usePagination} from "../../utils/usePagination";
import {usePayList} from "./usePayList";
import LoadMore from '../../components/loadmore/index.vue'
import {fetchPayInfo,PayRefund} from "../../api/pay";
import {useStore} from "vuex";
import {usePrice} from "../../utils/usePrice";
const {getPrice} = usePrice()

const curTab = ref('1')
const tabs = [
  {
    value: '1',
    title: '未缴清'
  },
  {
    value: '2',
    title: '已缴清'
  },
  {
    value: '3',
    title: '申请退款'
  },
  {
    value: '4',
	title: '退款审核通过'
    //title: '已退款'
  },
  {
    value: '5',
    title: '已失效'
  },
  {
    value: '0',
    title: '已取消'
  }
]

const {total, payList, initPayList,initpayRefout}:any = usePayList()
const pageSize = 20
const {page,loadStatus} = usePagination({
  page: 1,
  pageSize,
  onPageChange: initPayList,
  startReachBottom: true,
  args: curTab
})

watchEffect(() => {
  loadStatus.value = total.value <= pageSize ? 'over' : 'loadmore'
})

async function tabSelect(tab: string){
  curTab.value = tab
  page.value = 1
  // await initData()
}

const {state, getters} = useStore()

function applyRefund(JFD_ID: string,item:any){
	uni.showModal({
		title: '请确认退款信息',
		content: "姓名:" + item.STUDENTNAME + "\n" + "课程信息:" + item.CLASSNAME  + "\n" + "金额：" + item.SFJE,
		success: (res) => {
			if (res.confirm){
				let {CUSER_ID} = uni.getStorageSync("userInfo")
				let ApyObj = {
					JFD_ID:JFD_ID,
					OPERATOR_ID:CUSER_ID
				}
				PayRefund({...ApyObj}).then(res=>{
					if (res.ERROR[0].errcode == '0'){
						setTimeout(() => {
						  page.value = -1
						  page.value = 1
							uni.showToast({
								title: "申请退款成功",
								icon: 'none',
								mask: true
							})
						},500)
					}else {
						uni.showToast({
								title: res.ERROR[0].error,
								icon: 'none',
								mask: true
						})
					}
				})
			}
		}
	})
	
}

async function doPay(orderNo: string, money: number,item:any){
	uni.showModal({
		title: '请核对信息',
		content: "姓名:" + item.STUDENTNAME + "\n" + "课程信息:" + item.CLASSNAME  + "\n" + "金额：" + item.SFJE,
		success: res => {
			if(res.confirm){
				pay(orderNo,money)
			}
		},
		fail: () => {},
		complete: () => {}
	});
  
}
async function pay(orderNo: string, money: number){
	try {
	  const res = await fetchPayInfo({
	    openid: getters.OPENID,
	    total_fee: money * 100 + '',
	    order_code: orderNo,
        OPERATOR_ID: state.user.userInfo.CUSER_ID
	  })
	  if (res.meta.status === 200){
	    const {timeStamp,nonceStr,paySign,signType} = res.message
	    uni.requestPayment({
	      provider: 'wxpay',
	      orderInfo: '',
	      timeStamp,
	      nonceStr,
	      package: res.message.package,
	      paySign,
	      signType,
	      success: () => {
	        uni.showToast({
	          title: '支付成功',
	          icon: 'success',
	          mask: true,
	          success: () => {
	            setTimeout(() => {
	              page.value = -1
	              page.value = 1
	            },5500)
	          },
				complete() {
					setTimeout(()=>{
						initpayRefout(orderNo)
					},5000)
				}
	        })
	      },
	      fail: ({errMsg}) => {
	      },
	    })
	  }else {
	    uni.showToast({
	      title: res.meta.msg,
	      icon: 'none',
	      mask: true
	    })
	  }
	
	}catch (err){
	  uni.showToast({
	    title: '支付失败，系统异常',
	    icon: 'none',
	    mask: true
	  })
	}
}
function toDZGZ(DZGZ: string){
  if (DZGZ.length === 0){
    return
  }
  uni.navigateTo({
    url:`/pages/pay/DZGZ?DZGZ=${DZGZ}`
  })
}

</script>

<style scoped lang="scss">
  .PayList{
    box-sizing: border-box;
    padding-bottom: constant(safe-area-inset-bottom);  ///兼容 IOS<11.2/
    padding-bottom: env(safe-area-inset-bottom);  ///兼容 IOS>11.2/
  }
</style>
